package lab6.systemCustom;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

public class Logger implements Observer {

	/**
	 * Referinta catre BufferedWriter pentru fisierul de jurnal de pe disk.
	 */
	private BufferedWriter out;

	/**
	 * Constructs a logger component. </br>
	 * 
	 * A logger component subscribes to show events at the time of creation.
	 */
	public Logger(String logFileName) {
		// Subscribe to EV_SHOW event.
		EventBus.subscribeTo(EventBus.EV_SHOW, this);

		try {
			out = new BufferedWriter(new FileWriter(logFileName, true));
		} catch (IOException e) {
			// Daca apare IOException atunci se afiseaza exceptia si se iese.
			System.err.println("IOException in Logger. Conexiunea catre fisierul de log '" + logFileName + "' nu a putut fi realizata.");
			System.exit(1);
		}
	}

	/**
	 * Event handler of the logger component. On receiving a show event, the
	 * attached <code>String</code> object is written into the log file.
	 * 
	 * @param event
	 *            an event object. (caution: not to be directly referenced)
	 * @param param
	 *            a parameter object of the event. (to be cast to appropriate
	 *            data type)
	 */
	public void update(Observable event, Object param) {
		// Write the event parameter (a string) into the log file.
		try {
			out.write((String) param + "\n");
			out.flush();
		} catch (IOException e) {
			System.err.println("Logger nu a putut efectua jurnalizarea.");
		}
	}

}